//
//  BrandsViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/25.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "BrandsViewController.h"
#import "SearchStoreTableViewCell.h"
#import "ShopViewController.h"
#import "StoresListViewController.h"
static NSString * cellIndentfier = @"SearchStoreTableViewCell";


@interface BrandsViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIView *tapyView;
@property (strong, nonatomic) IBOutlet UITableView *tableVIew;
@property (strong, nonatomic) IBOutlet UITableView *tapysTableView;
@property(nonatomic,strong)NSString * floorStr;
@property(nonatomic,strong)NSString * typeStr;
@property(nonatomic,strong)NSString * pickStr;
@property(nonatomic,strong)NSMutableArray * storeArray;
@property(nonatomic,strong)NSMutableArray * typesArray;
@property(nonatomic,strong)NSDictionary * choseTypeDic;
@property (strong, nonatomic) NSMutableArray *storeClassifyArrary;
@property (strong, nonatomic) IBOutlet UIButton *floorButton;
@property (strong, nonatomic) IBOutlet UIButton *typeButton;
@property (strong, nonatomic) IBOutlet UIButton *choseButton;
@property (strong, nonatomic) IBOutlet UIButton *maskButton;
@property (strong, nonatomic) IBOutlet UIButton *floorSmallButton;
@property (strong, nonatomic) IBOutlet UIButton *typeSmallButton;
@property (strong, nonatomic) IBOutlet UIButton *choseSmallButton;
@property(nonatomic,strong)UIButton * currentButton;

@end

@implementation BrandsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO =  1;
    _typesArray = [NSMutableArray array];
    _storeArray = [NSMutableArray array];
    _choseTypeDic = [@{@"floor":@"",@"type":@"",@"pick":@""}mutableCopy];
    _floorStr = @"";
    _typeStr = @"";
    _pickStr = @"";
    self.storeClassifyArrary = [NSMutableArray array];
    [self initViewLayout];
    [self getTypes];
    [self addRefreshing];
    
}
- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.tapyView];
    
    [self.tableVIew registerNib:[UINib nibWithNibName:cellIndentfier bundle:nil] forCellReuseIdentifier:cellIndentfier];
    _tableVIew.scrollEnabled = YES;
    _tapysTableView.dataSource = self;
    _tapysTableView.delegate = self;
}
- (void)getStoresList{
        
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];

        [dic setObject:_floorStr forKey:@"mstoStair"];
        [dic setObject:_typeStr forKey:@"mstoTypeId"];
        [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
        [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_queryShopRanking withHttpType:@"POST" withTag:SX_SX_queryShopRanking];
        
}
    
- (void)getTypes{
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"20169615" forKey:@"mstyId"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_queryShopTypes withHttpType:@"POST" withTag:SX_SX_queryShopTypes];
    }
    
#pragma mark -- 添加刷新数据
    - (void)addRefreshing{
        self.tableVIew.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            int64_t delayInSeconds = 8.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.tableVIew.header endRefreshing];
            });
            self.pageNO = 1;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //请求商家数据
                [self getStoresList];
            });
        }];
        // 马上进入刷新状态
        [self.tableVIew.header beginRefreshing];
    }
    //加载更多数据
    - (void)loadMoreData{
        if (self.storeArray.count == _totle) {
            [self.tableVIew.footer endRefreshing];
        }else{
            self.pageNO = self.pageNO + 1;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //请求商家数据
                [self getStoresList];
            });
        }
        
    }
    
    
- (IBAction)choseTypeHandel:(UIButton*)sender {
        
        [_typesArray removeAllObjects];
    
    UIButton * button = [[UIButton alloc]init];
    if (sender == _floorButton) {
        button = _floorSmallButton;
    }else if(sender == _choseButton){
        button = _choseSmallButton;
    }else{
        button = _typeSmallButton;
    }
    
    if (button != _currentButton) {
        [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
        _currentButton = button;
    }
        if (sender == _floorButton) {
            _floorButton.selected = YES;
            _floorSmallButton.selected = YES;
            _typeButton.selected = NO;
            _typeSmallButton.selected = NO;
            _choseButton.selected = NO;
            _choseSmallButton.selected = NO;
              [_floorSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
            _typesArray =[@[@"全部",@"B1休闲美食",@"1F时尚服饰",@"2F儿童主题",@"3F名表饰品",@"4F餐饮美食",@"5F休闲娱乐"]mutableCopy];
//            _tapysTableView.dataSource = self;
//            _tapysTableView.delegate = self;
            [_tapysTableView reloadData];
        }else if (sender == _typeButton){
            _floorButton.selected = NO;
            _floorSmallButton.selected = NO;
            _typeButton.selected = YES;
            _typeSmallButton.selected = YES;
            _choseButton.selected = NO;
            _choseSmallButton.selected = NO;
            [_typeSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
            if (self.storeClassifyArrary.count < 1) {
                [self getTypes];
            }else{
                [_tapysTableView reloadData];
            }
            
        }else{
            _floorButton.selected = NO;
            _floorSmallButton.selected = NO;
            _typeButton.selected = NO;
            _typeSmallButton.selected = NO;
            _choseButton.selected = YES;
            _choseSmallButton.selected = YES;
            [_choseSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
            _typesArray =[@[@"默认",@"销量最高",@"折扣优惠"]mutableCopy];
//            _tapysTableView.dataSource = self;
//            _tapysTableView.delegate = self;
            [_tapysTableView reloadData];
        }
        
        [UIView animateWithDuration:0.5 animations:^{
            if(_typeButton.selected){
                _tapysTableView.frame = flexibleFrame(CGRectMake(0, 109, 320, 45*_storeClassifyArrary.count), YES);
            }else{
                _tapysTableView.frame = flexibleFrame(CGRectMake(0, 109, 320, 45*_typesArray.count), YES);
            }
            
        }completion:^(BOOL finished) {
            _maskButton.hidden = NO;
        }];
        
        
        
    }
- (IBAction)closeTypes:(UIButton *)sender {
        _maskButton.hidden = YES;
        [UIView animateWithDuration:0.5 animations:^{
            _tapysTableView.frame = flexibleFrame(CGRectMake(0, 109, 320, 0), YES);
        }];
    [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];

}

#pragma mark ====旋转动画======
-(CABasicAnimation *)rotation:(float)dur degree:(float)degree direction:(int)direction repeatCount:(int)repeatCount
{
    CATransform3D rotationTransform = CATransform3DMakeRotation(degree, 0, 0, direction);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
    animation.duration  =  dur;
    animation.autoreverses = NO;
    animation.cumulative = NO;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = repeatCount;
    animation.delegate = self;
    
    return animation;
    
}


#pragma mark -- UITableViewDataSource
    
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
        return 1;
    }
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (tableView == _tableVIew) {
            return 95*VerticalRatio();
            
        }else{
            return 45*VerticalRatio();
        }
    }
    
    
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        if (tableView == _tapysTableView) {
            if (_typeButton.selected) {
                return _storeClassifyArrary.count;
            }
            return _typesArray.count;
        }else{
            return _storeArray.count;
        }
    }
    
    
    
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        if (tableView != _tableVIew) {
            static NSString * cellIdentifier = @"CELL";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell==nil) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            
            for (UIView *view in cell.subviews) {
                if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                    [view removeFromSuperview];
                }
            }
            UIImageView  * imageView = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(300, 16, 8, 13), YES)];
            imageView.image = [UIImage imageNamed:@"jiantou"];
            
            
            UILabel * label = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(15, 0, 280, 45), YES)];
            
            label.textColor = [UIColor colorWithWhite:0.094 alpha:1.000];
            label.textAlignment = NSTextAlignmentLeft;
            label.font = [UIFont systemFontOfSize:15*VerticalTexeRatio()];
            if (_typeButton.selected) {
                label.text = [NSString stringWithFormat:@"%@",_storeClassifyArrary[indexPath.row][@"mstyName"]];
                if (indexPath == _choseTypeDic[@"type"]) {
                    label.textColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000];
                    imageView.image = [UIImage imageNamed:@"jiantou1"];
                }
            }else{
                label.text = _typesArray[indexPath.row];
                if (_floorButton.selected) {
                    if (indexPath == _choseTypeDic[@"floor"]) {
                        label.textColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000];
                        imageView.image = [UIImage imageNamed:@"jiantou1"];
                    }
                }else{
                    if (indexPath == _choseTypeDic[@"pick"]) {
                        label.textColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000];
                        imageView.image = [UIImage imageNamed:@"jiantou1"];
                    }
                }
            }
            [cell addSubview:imageView];
            [cell addSubview:label];
            
            UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 44, 320, 1), YES)];
            line.backgroundColor = [UIColor colorWithWhite:0.949 alpha:1.000];
            [cell addSubview:line];
            return cell;
        }else{
            SearchStoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentfier];
            if (cell == nil) {
                cell= [[SearchStoreTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentfier];
                
            }
            
            for (UIView *view in cell.subviews) {
                if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                    [view removeFromSuperview];
                }
            }
            
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            
            
            
            
            NSString * image = _storeArray[indexPath.row][@"mstoImag"];
            if (image.length>0) {
                [cell.storeImage sd_setImageWithURL:[NSURL URLWithString:image]];
            }else{
                cell.storeImage.image = [UIImage imageNamed:@"collection5"];
            }
            cell.storeName.text = _storeArray[indexPath.row][@"mstoName"];
            cell.storeAddress.text = _storeArray[indexPath.row][@"mstoAddress"];
            
            
            double score = [[NSString stringWithFormat:@"%.1f",[_storeArray[indexPath.row][@"storeScore"]floatValue]/2] doubleValue];
            
            CommitStarsView * starts = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(115, 37, 75, 15), YES) Stars:score];
            [cell addSubview:starts];
            cell.scoreLabel.text = [NSString stringWithFormat:@"%.1f分",score];
            cell.storeTypeLabel.text = [NSString stringWithFormat:@"%@",_storeArray[indexPath.row][@"mstyName"]];
            return cell;
        }
        return nil;
    }
    
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
        if (tableView != _tableVIew) {
            if (_floorButton.selected) {
                [_choseTypeDic setValue:indexPath forKey:@"floor"];
                if(indexPath.row == 0){
                    _floorStr = @"";
                }else{
                    _floorStr = [NSString stringWithFormat:@"%ld",indexPath.row-1];
                }
                [_floorButton setTitle:_typesArray[indexPath.row] forState:UIControlStateNormal];
                
                CGSize size = [_floorButton.titleLabel.text sizeWithFont:_floorButton.titleLabel.font];
                if (size.width>_floorButton.frame.size.width) {
                    size.width = _floorButton.frame.size.width-_floorSmallButton.frame.size.width;
                }
                _floorSmallButton.frame =CGRectMake(CGRectGetMinX(_floorButton.frame)+(_floorButton.frame.size.width-size.width)/2+size.width+1, _floorSmallButton.frame.origin.y, _floorSmallButton.frame.size.width, _floorSmallButton.frame.size.height);
            }else if(_typeButton.selected){
                [_choseTypeDic setValue:indexPath forKey:@"type"];
                _typeStr = [NSString stringWithFormat:@"%@",_storeClassifyArrary[indexPath.row][@"mstyId"]];
                [_typeButton setTitle:_storeClassifyArrary[indexPath.row][@"mstyName"] forState:UIControlStateNormal];
                
                CGSize size = [_typeButton.titleLabel.text sizeWithFont:_typeButton.titleLabel.font];
                if (size.width>_typeButton.frame.size.width) {
                    size.width = _typeButton.frame.size.width-_typeSmallButton.frame.size.width;
                }
                _typeSmallButton.frame =CGRectMake(CGRectGetMinX(_typeButton.frame)+(_typeButton.frame.size.width-size.width)/2+size.width+1, _typeSmallButton.frame.origin.y, _typeSmallButton.frame.size.width, _typeSmallButton.frame.size.height);
            }else{
                [_choseTypeDic setValue:indexPath forKey:@"pick"];
                _pickStr = [NSString stringWithFormat:@"%@",_typesArray[indexPath.row]];
                 [_choseButton setTitle:_typesArray[indexPath.row] forState:UIControlStateNormal];
                
                CGSize size = [_choseButton.titleLabel.text sizeWithFont:_choseButton.titleLabel.font];
                if (size.width>_choseButton.frame.size.width) {
                    size.width = _choseButton.frame.size.width-_choseSmallButton.frame.size.width;
                }
                _choseSmallButton.frame =CGRectMake(CGRectGetMinX(_choseButton.frame)+(_choseButton.frame.size.width-size.width)/2+size.width+1, _choseSmallButton.frame.origin.y, _choseSmallButton.frame.size.width, _choseSmallButton.frame.size.height);
            }
            
            
            [self addRefreshing];
            _maskButton.hidden = YES;
            [UIView animateWithDuration:0.5 animations:^{
                _tapysTableView.frame = flexibleFrame(CGRectMake(0, 109, 320, 0), YES);
            }];
            [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];

        }else{
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            ShopViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Shop"];
            page.storeId = _storeArray[indexPath.row][@"mstoId"];
            [self.navigationController   pushViewController:page animated:YES];
        }
        
        
    }
    
#pragma   mark---- GetADBanner Request Delegate
    
-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
        [_tableVIew.header endRefreshing];
        [_tableVIew.footer endRefreshing];
        if (tag == SX_SX_queryShopRanking){
            if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
                
                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
                
            }else  {
                dispatch_async(dispatch_get_main_queue(), ^{
                    _totle = [database[@"result"][@"totalResults"] integerValue];
                    if (_totle > PageSize) {
                        __weak __typeof(self) weakSelf = self;
                        if (!self.tableVIew.footer) {
                            // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                            self.tableVIew.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                                [weakSelf loadMoreData];
                            }];
                        }
                    }
                    if (self.pageNO == 1) {
                        [self.storeArray removeAllObjects];
                    }
                    NSArray *arr = database[@"result"][@"pageRecord"];
                    for (id entity in arr) {
                        [self.storeArray addObject:entity];
                    }
                    _tableVIew.dataSource = self;
                    _tableVIew.delegate = self;
                    [_tableVIew reloadData];
                    
                });
            }
        }else if (tag == SX_SX_queryShopTypes){
            if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
                
                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
                
            }else  {
                _storeClassifyArrary = database[@"result"];
                [_tapysTableView reloadData];
                
            }
        }
    }
    
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
        
        //
        [self dismissWaitDialog];
        
        
    }

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
#pragma mark == 搜索
- (IBAction)search:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    
    StoresListViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"StoresList"];
    [self.navigationController   pushViewController:page animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
